package com.campus.dao.impl;

import com.campus.dao.TeacherDao;
import com.campus.model.Teacher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * @desc: 教师数据访问对象实现类
 * @author: hjm
 * @date: 2024/11/22
 */
@Repository
public class TeacherDaoImpl implements TeacherDao {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    /**
     * 创建教师
     * @param teacher 教师对象
     * @return 受影响的行数
     */
    @Override
    public int createTeacher(Teacher teacher) {
        String sql = "INSERT INTO t_manager_teacher (teacher_name, subject, profession, school, introduce, login_id) VALUES (?, ?, ?, ?, ?, ?)";
        return jdbcTemplate.update(sql, teacher.getTeacherName(), teacher.getSubject(), teacher.getProfession(), teacher.getSchool(), teacher.getIntroduce(), teacher.getLoginId());
    }

    /**
     * 根据ID获取教师信息
     * @param id 教师ID
     * @return 教师对象
     */
    @Override
    public Teacher getTeacherById(int id) {
        String sql = "SELECT * FROM t_manager_teacher WHERE id = ?";
        return jdbcTemplate.queryForObject(sql, new Object[]{id}, (rs, rowNum) -> {
            Teacher teacher = new Teacher();
            teacher.setId((long) rs.getInt("id"));
            teacher.setTeacherName(rs.getString("teacher_name"));
            teacher.setSubject(rs.getString("subject"));
            teacher.setProfession(rs.getString("profession"));
            teacher.setSchool(rs.getString("school"));
            teacher.setIntroduce(rs.getString("introduce"));
            teacher.setLoginId((long) rs.getInt("login_id"));
            return teacher;
        });
    }

    /**
     * 根据筛选条件获取教师列表
     * @param subject 学科
     * @param school 学校
     * @return 教师列表
     */
    @Override
    public List<Teacher> getTeachersByFilter(String subject, String school) {
        StringBuilder sql = new StringBuilder("SELECT * FROM t_manager_teacher WHERE 1=1");
        if (subject != null && !subject.isEmpty()) {
            sql.append(" AND subject = '").append(subject).append("'");
        }
        if (school != null && !school.isEmpty()) {
            sql.append(" AND school = '").append(school).append("'");
        }
        return jdbcTemplate.query(sql.toString(), (rs, rowNum) -> {
            Teacher teacher = new Teacher();
            teacher.setId((long) rs.getInt("id"));
            teacher.setTeacherName(rs.getString("teacher_name"));
            teacher.setSubject(rs.getString("subject"));
            teacher.setProfession(rs.getString("profession"));
            teacher.setSchool(rs.getString("school"));
            teacher.setIntroduce(rs.getString("introduce"));
            teacher.setLoginId((long) rs.getInt("login_id"));
            return teacher;
        });
    }
}